package client.common.util;

import java.security.Key;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;


/**
 * 使用jwt令牌来验证是否登录了
 */
@Slf4j
public class JWTUtilS {
    private static ObjectMapper objectMapper = new ObjectMapper();

    //1天
    private static final long EXPIRATION = 60 * 60 * 60 * 1000;

    private static final byte[] keys = UUID.randomUUID().toString().getBytes();

    public static String getToken(Map<String, Object> claims) {
        try {
            claims.put("expire_time", System.currentTimeMillis() + EXPIRATION);

            return JWTUtil.createToken(claims, keys);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    //将类转换为Map对象
    public static String getToken(Object claims) {
        try {
            String s = objectMapper.writeValueAsString(claims);

            Map<String, Object> map = objectMapper.readValue(s, Map.class);

            return getToken(map);

        } catch (JsonMappingException e) {
            log.error("在反序列化对象的时候出现了错误: {}", e.getMessage(), e);
            return null;
        } catch (JsonProcessingException e) {
            log.error("在序列化对象的时候出现了错误: {}", e.getMessage(), e);
            return null;
        }
    }

    public static JWTPayload parseToken(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        return jwt.getPayload();
    }
}
